package com.weiyi.admin.models.ums.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.weiyi.admin.domain.AdminUserDetails;
import com.weiyi.admin.models.ums.mapper.UmsResourceMapper;
import com.weiyi.admin.models.ums.mapper.UmsRoleMapper;
import com.weiyi.admin.models.ums.model.UmsResource;
import com.weiyi.admin.models.ums.model.UmsRole;
import com.weiyi.admin.models.ums.service.UmsAdminService;
import com.weiyi.admin.models.ums.mapper.UmsAdminMapper;
import com.weiyi.admin.models.ums.model.UmsAdmin;
import com.weiyi.common.common.exception.ApiException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 后台用户表 服务实现类
 * </p>
 *
 * @author PZC
 * @since 2022-10-12
 */
@Service
public class UmsAdminServiceImpl extends ServiceImpl<UmsAdminMapper, UmsAdmin> implements UmsAdminService {

    @Autowired
    UmsAdminCacheServiceImpl adminCacheService;

    @Autowired
    UmsResourceMapper resourceMapper;
    
    @Autowired
    UmsRoleMapper roleMapper;


    //@Override
    public List<UmsResource> getResourceList(Long adminId) {
        List<UmsResource> resourceList = adminCacheService.getResourceList(adminId);
        if(CollUtil.isNotEmpty(resourceList)){
            return  resourceList;
        }

        resourceList = resourceMapper.getResourceList(adminId);
        if(CollUtil.isNotEmpty(resourceList)){
            adminCacheService.setResourceList(adminId,resourceList);
        }
        return resourceList;
    }

   // @Override
    public AdminUserDetails loadUserByUserName(String name) {
        UmsAdmin admin = getAdminByUsername(name);
        if(admin != null){
            //List<UmsResource> resourceList = getResourceList(admin.getId());

            List<UmsRole> roleList = getRoleList(admin.getId());
            AdminUserDetails adminUserDetails = new AdminUserDetails(admin,roleList);
            return adminUserDetails;
        }
        throw new ApiException("用户不存在");
    }

    public List<UmsRole> getRoleList(Long id) {
        return roleMapper.getRoleList(id);
    }

    //@Override
    public UmsAdmin getAdminByUsername(String username) {
        UmsAdmin admin = adminCacheService.getAdmin(username);
        if(admin!=null) return  admin;

        QueryWrapper<UmsAdmin> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(UmsAdmin::getUsername,username);
        List<UmsAdmin> adminList = list(wrapper);
        if (adminList != null && adminList.size() > 0) {
            admin = adminList.get(0);
            adminCacheService.setAdmin(admin);
            return admin;
        }
        return null;
    }
}
